import router from '@/router';
import { userStore } from '@/store';
import io from 'socket.io-client';
export default {
    //@ts-ignore
    install: (app) => {
        const socket = io('http://localhost:3000', {
            autoConnect: true,
            reconnection: true,
            reconnectionAttempts: Infinity, // 尝试重连的次数，默认是5次
            reconnectionDelay: 1000, // 第一次重连延迟时间，默认是1000ms
            reconnectionDelayMax: 5000,
        });
        const user = userStore()
        socket.on('connect', () => {
            console.log('socket connect')
            socket.emit('login', { id: userStore().userInfo.user_id, nickname: userStore().userInfo.nickname })
        })
        socket.on('message', (data: any) => {
            if (!user.chaterInfoList.some(item => item.user_id == data.senderId)) {
                user.getChaterInfo(data.senderId)
                user.addMessageInfo(data.senderId)
            }

            const path = router.currentRoute.value.path;
            if (path !== '/ChatInterface' || data.senderId !== user.currentInfo.user_id) {
                user.addUnReadNum(data.senderId)
            }
            if (data.senderId !== user.userInfo.user_id) {
                user.addMessage(data, data.senderId)
            }
        })
        socket.on('messageList', async (data: any) => {
            console.log('连接成功', data);
            data.forEach(async (i: any,index:any) => {
                    if (!user.chaterInfoList.some(item => item.user_id == i.senderId)) {
                        await user.getChaterInfo(i.senderId)
                         user.addMessageInfo(i.senderId)
                     }
                     const path = router.currentRoute.value.path;
                     if (path !== '/ChatInterface' || i.senderId !== user.currentInfo.user_id) {
                         user.addUnReadNum(i.senderId)
                     }
                     if (i.senderId !== user.userInfo.user_id) {
                         user.addMessage(i, i.senderId)
                     }  
            })
        })
        socket.on('disconnect', () => {
            console.log('断开连接');
            socket.connect();
            socket.emit('login', { id: userStore().userInfo.user_id, nickname: userStore().userInfo.nickname })
        })
        app.config.globalProperties.$socket = socket
        app.provide('socket', socket)
    }
}
